<template>
  <div>
    <div style="display: flex;justify-content: space-between; width: 100%">
      <el-form
        :model="formData"
        label-position="left"
        label-width="100px"
        :rules="ruleForm"
        ref="ruleForm"
      >
        <el-form-item label="景区名称" prop="name">
          <el-input v-model="formData.name" type="text" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="景区地址" prop="address">
          <el-input v-model="formData.address" type="text" placeholder="请输入地址" />
        </el-form-item>
        <div style="display: flex">
          <el-form-item label="营业时间"></el-form-item>
          <el-form-item label="非周末" prop="start_time"  label-width="70px">
            <el-time-picker
              is-range
              v-model="formData.start_time"
              range-separator="至"
              format="HH:mm"
              value-format="timestamp"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围">
            </el-time-picker>
          </el-form-item>
          <el-form-item label="周末" prop="end_time" label-width="50px" style="margin-left: 100px">
            <el-time-picker
              is-range
              v-model="formData.end_time"
              range-separator="至"
              format="HH:mm"
              value-format="timestamp"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围">
            </el-time-picker>
          </el-form-item>
        </div>
        <el-form-item label="景区图片" prop="img_arr">
          <el-upload
            action="https://up.qiniup.com"
            :class="formData.img_arr && formData.img_arr.length > 0 ? 'hidden':''"
            :limit="1"
            :data="uploadData"
            accept="image/*"
            :file-list="formData.img_arr"
            list-type="picture-card"
            :before-upload="beforeAvatarUpload"
            :on-success="upSuccess"
            :on-exceed="overMax"
            :on-remove="handleRemove"
          >
            <i slot="default" class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="景区地图" prop="map_img">
          <el-upload
            action="https://up.qiniup.com"
            :class="formData.map_img && formData.map_img.length > 0 ? 'hidden':''"
            :limit="1"
            :data="uploadData"
            accept="image/*"
            :file-list="formData.map_img"
            list-type="picture-card"
            :before-upload="beforeAvatarUpload"
            :on-success="(response,file,fileList) => {upSuccess(response,file,fileList,'map')}"
            :on-exceed="overMax"
            :on-remove="(file,fileList) => {handleRemove(file,fileList,'map')}"
          >
            <i slot="default" class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="西南经纬度" class="is-required" prop="map_img_south_west">
          <el-input v-model="south_west.lng" style="width: 200px;margin-right: 12px"
                    oninput="value=value.replace(/[^\d^\.]+/g,'')"
                    @blur="blurLngAddLat"
                    @input="inputLngAddLat"
                    type="number" placeholder="请输入景区西南经度" />
          <el-input v-model="south_west.lat" style="width: 200px"
                    oninput="value=value.replace(/[^\d^\.]+/g,'')"
                    @blur="blurLngAddLat"
                    @input="inputLngAddLat"
                    type="number" placeholder="请输入景区西南纬度" />
        </el-form-item>
        <el-form-item label="中心经纬度" class="is-required" prop="map_img_center">
          <el-input v-model="center_west.lng" disabled style="width: 200px;margin-right: 12px"
                    oninput="value=value.replace(/[^\d^\.]+/g,'')"
                    type="number" placeholder="请输入景区中心经度" />
          <el-input v-model="center_west.lat" disabled style="width: 200px"
                    oninput="value=value.replace(/[^\d^\.]+/g,'')"
                    type="number" placeholder="请输入景区中心纬度" />
        </el-form-item>
        <el-form-item label="东北经纬度" class="is-required" prop="map_img_north_east">
          <el-input v-model="north_west.lng" style="width: 200px;margin-right: 12px"
                    oninput="value=value.replace(/[^\d^\.]+/g,'')"
                    @blur="blurLngAddLat"
                    @input="inputLngAddLat"
                    type="number" placeholder="请输入景区东北经度" />
          <el-input v-model="north_west.lat" style="width: 200px"
                    oninput="value=value.replace(/[^\d^\.]+/g,'')"
                    @blur="blurLngAddLat"
                    @input="inputLngAddLat"
                    type="number" placeholder="请输入景区东北纬度" />
          <div style="color:#97a8be;">
            提示：删除任意经纬度可以重新选点
          </div>
          <div class="amap-wrapper">
            <el-amap-search-box class="search-box" :search-option="searchOption" :on-search-result="onSearchResult"
            ></el-amap-search-box>
            <el-amap vid="amap" :zoom="zoom" :center="center" class="amap-demo" :events="events">
              <el-amap-marker v-for="(marker, index) in markers" :vid="index"
                              :position="marker.position" :events="marker.events"
                              animation="AMAP_ANIMATION_DROP"
              ></el-amap-marker>
            </el-amap>
          </div>
        </el-form-item>
        <el-form-item label="联系电话" prop="phonenum">
          <el-input v-model="formData.phonenum" style="width: 200px" type="number" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="自定义标签" prop="label_arr">
          <el-tag
            style="margin-right: 8px"
            v-for="(tag,index) in tags" :key="index"
            closable
            @close="handleClose(tag,index)">
            {{tag.name}}
          </el-tag>
          <el-input
            class="input-new-tag"
            v-if="inputVisible"
            v-model="inputValue"
            ref="saveTagInput"
            style="width: 90px;"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          >
          </el-input>
          <el-button v-if="tags.length < 2" class="button-new-tag" size="small" @click="showInput">+ 增加</el-button>
        </el-form-item>
        <el-form-item label="音频文件" prop="audit_arr">
          <el-upload
            class="upload-demo"
            :limit="1"
            action="https://up.qiniup.com"
            :data="uploadData"
            accept="audio/*"
            :before-upload="beforeAvatarUpload"
            :on-success="(response,file,fileList) => {upSuccess(response,file,fileList,'audio')}"
            :on-remove="(file,fileList) => {handleRemove(file,fileList,'audio')}"
            :on-exceed="() => { $message.warning({ message: '上传音频最大为1' }) }"
            :file-list="formData.audit_arr">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="详情内容" prop="content_html">
          <Tinymce v-model="formData.content_html" :height="300" />
        </el-form-item>
      </el-form>
    </div>
    <div style="margin: 5% 0 0 5%;">
      <el-button plain style="margin-right: 3%;" @click="$emit('close')">取消</el-button>
      <el-button type="primary" @click="handleChangeStudentInfo">保存</el-button>
    </div>
  </div>
</template>

<script>
import WxDialog from '@/components/WxDialog'
import TableMixins from '@/components/WxTables/mixins'
import Tinymce from '@/components/Tinymce/Tinymce'
import { tourScenicLabelCreate, tourScenicLabelDestroy } from '@/api/scenic'
var validPhone = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入电话号码'))
  } else if (!/^1[3|4|5|7|8][0-9]\d{8}$/.test(value)) {
    callback(new Error('请输入正确的11位手机号码'))
  } else {
    callback()
  }
}
export default {
  name: 'ScenicInfo',
  components: {
    WxDialog,
    Tinymce
  },
  mixins: [TableMixins],
  props: {
    formData: {
      type: Object
    }
  },
  data() {
    return {
      tags: [],
      inputVisible: false,
      inputValue: '',
      qiNiuToken: '',
      ruleForm: {
        name: [
          { required: true, message: '请填写名称', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请填写地址', trigger: 'blur' }
        ],
        start_time: [
          { required: true, message: '请选择营业时间', trigger: 'blur' }
        ],
        end_time: [
          { required: true, message: '请选择营业时间', trigger: 'blur' }
        ],
        img_arr: [
          { required: true, message: '请选择景区图片', trigger: 'blur' }
        ],
        map_img: [
          { required: true, message: '请选择景区地图', trigger: 'blur' }
        ],
        phonenum: [
          { required: true, trigger: 'blur', validator: validPhone }
        ],
        content_html: [
          { required: true, message: '请填写简介', trigger: 'blur' }
        ],
      },
      parentIndex: 0,
      editIsAdd: '',
      south_west: {},
      center_west: {},
      north_west: {},
      isType: '',
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      selectClassList: [],
      addParentsList: {
        relationship: '',
        name: '',
        tel_num: '',
        img: ''
      },
      editJanitor: false,

      //地图参数
      zoom: 11,
      center: [121.006725,29.144079],
      markers: [],
      searchOption: {
        city: '天台县',
        citylimit: false
      },
      events: {
        click: (e) => {
          const item_obj = {
            position: [e.lnglat.lng, e.lnglat.lat]
          }
          if(this.markers.length < 2) {
            if(this.markers.length === 1 ) {
              this.$set(this.south_west,'lng',this.markers[0].position[0])
              this.$set(this.south_west,'lat',this.markers[0].position[1])
              this.$set(this.north_west,'lng',item_obj.position[0])
              this.$set(this.north_west,'lat',item_obj.position[1])
              this.$set(this.center_west,'lng',(e.lnglat.lng + this.markers[0].position[0])/2)
              this.$set(this.center_west,'lat',(e.lnglat.lat + this.markers[0].position[1])/2)
              const item = {
                position: [this.center_west.lng, this.center_west.lat]
              }
              this.markers.push(item)
            }
            this.markers.push(item_obj)
          }
        }
      }
    }
  },
  created(){
    this.firstLoad = false
    if(this.formData.label_arr) {
      this.tags = this.formData.label_arr
    }
    if(this.formData.map_img_north_east) {
      this.north_west = {
        lng: this.formData.map_img_north_east.split(',')[0],
        lat: this.formData.map_img_north_east.split(',')[1],
      }
    }
    if(this.formData.map_img_center) {
      this.center_west = {
        lng: this.formData.map_img_center.split(',')[0],
        lat: this.formData.map_img_center.split(',')[1],
      }
    }
    if(this.formData.map_img_south_west) {
      this.south_west = {
        lng: this.formData.map_img_south_west.split(',')[0],
        lat: this.formData.map_img_south_west.split(',')[1],
      }
    }
    this.blurLngAddLat()
  },
  methods: {
    /**
     * 搜索地图点位
     * @param pois
     */
    onSearchResult(pois) {
      let latSum = 0
      let lngSum = 0
      if (pois.length > 0) {
        pois.forEach(poi => {
          let { lng, lat } = poi
          lngSum += lng
          latSum += lat
        })
        let center = {
          lng: lngSum / pois.length,
          lat: latSum / pois.length
        }
        this.center = [center.lng, center.lat]
      }
    },
    /**
     * 值改变关闭点位
     */
    inputLngAddLat() {
      this.markers = []
    },
    /**
     * 失焦重新计算点位
     */
    blurLngAddLat() {
      if(this.south_west.lng && this.south_west.lat && this.north_west.lng && this.north_west.lat && !this.markers.length) {
        this.center_west.lng = (Number(this.south_west.lng) + Number(this.north_west.lng))/2
        this.center_west.lat = (Number(this.south_west.lat) + Number(this.north_west.lat))/2
        const item1 = {
          position: [this.south_west.lng, this.south_west.lat]
        }
        const item2 = {
          position: [this.center_west.lng, this.center_west.lat]
        }
        const item3 = {
          position: [this.north_west.lng, this.north_west.lat]
        }
        this.markers.push(item1)
        this.markers.push(item2)
        this.markers.push(item3)
      }
    },
    /**
     * 监控上传数量
     */
    overMax() {
      this.$message.warning({ message: '上传图片最大为1张' })
    },
    /**
     * 得到上传成功的文件
     * @param fileList
     * @param type
     */
    getFile(fileList,type) {
      if(type === 'audio'){
        this.$set(this.formData,'audit_arr',fileList)
      }else if(type === 'map'){
        this.$set(this.formData,'map_img',fileList)
      }else{
        this.$set(this.formData,'img_arr',fileList)
      }
    },
    /**
     * 删除图片
     * @param fileList
     * @param type
     */
    deleteFile(fileList,type) {
      if(type === 'audio'){
        this.$set(this.formData,'audit_arr',fileList)
      }else if(type === 'map'){
        this.$set(this.formData,'map_img',fileList)
      }else{
        this.$set(this.formData,'img_arr',fileList)
      }
    },
    /**
     * 删除标签
     */
    handleClose(tag,index) {
      this.tags.splice(index, 1);
      if(this.formData.id) {
        const list = {
          scenic_id:this.formData.id,
          tour_scenic_label_ids:tag.id,
        }
        tourScenicLabelDestroy(list).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功')
          }
        })
      }
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    /**
     * 添加标签
     */
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.tags.push({name: inputValue})
        if(this.formData.id) {
          const list = {
            scenic_id: this.formData.id,
            name: inputValue
          }
          tourScenicLabelCreate(list).then(res => {
            if (res.code === 200) {
              // this.formData = res.data
              this.$message.success('添加成功')
            }
          })
        }
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    handleIsAdd(type, index) {
      this.editIsAdd = type
      this.parentIndex = index
      if (type === 'create') {
        this.isType = '添加'
        this.addParentsList = {}
      }
      if (type === 'edit') {
        this.isType = '编辑'
        this.addParentsList = JSON.parse(JSON.stringify(this.formData.parents[index]))
      }
      this.editJanitor = true
    },
    beforeAddAvatarUpload(file) {
      uploadNormalFile(file, (res) => {
        this.$set(this.addParentsList, 'img', res)
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    /**
     * 保存
     */
    handleChangeStudentInfo() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if(!this.north_west.lng && !this.north_west.lat) return this.$message.warning('请输入东北经纬度')
          if(!this.south_west.lng && !this.south_west.lat) return this.$message.warning('请输入西南经纬度')
          let list = JSON.parse(JSON.stringify(this.formData));
          if(this.formData.img_arr && this.formData.img_arr.length){
            list.img_arr = this.formData.img_arr.map(item => {
              return item.name ? this.img_url + item.response.key : this.img_url + item.uid
            })
          }
          if(this.formData.audit_arr && this.formData.audit_arr.length){
            list.audit_arr = this.formData.audit_arr.map(item => {
              return item.type === 0 ? this.img_url + item.uid : this.img_url + item.response.key
            })
          }
          if(this.formData.map_img && this.formData.map_img.length){
            list.map_img =this.formData.map_img[0].name ?
              this.img_url + this.formData.map_img[0].response.key : this.img_url + this.formData.map_img[0].uid
          }
          list.map_img_south_west = [ this.south_west.lng,this.south_west.lat ].join(',')
          list.map_img_center = [ this.center_west.lng,this.center_west.lat ].join(',')
          list.map_img_north_east = [ this.north_west.lng,this.north_west.lat ].join(',')
          for (let i in list){
            if(['start_time'].includes(i)){
              list.work_day_start = this.$dayjs(list[i][0]).format('HH:mm')
              list.work_day_end = this.$dayjs(list[i][1]).format('HH:mm')
            }
            if(['end_time'].includes(i)){
              list.rest_day_start = this.$dayjs(list[i][0]).format('HH:mm')
              list.rest_day_end = this.$dayjs(list[i][1]).format('HH:mm')
            }
          }
          for (let i in list){
            if(['start_time','end_time'].includes(i)){
              delete list[i]
            }
          }
          if(this.tags.length){
            list.label_arr = this.tags.map(res=>res.name)
          }
          this.$emit('saveFrom',list)
        } else {
          return false;
        }
      });
    },
  }
}
</script>
<style scoped>
.amap-wrapper {
  position: relative;
  height: 24rem;
  margin-top: 8px;
}

.amap-demo {
  height: 100%;
}

.search-box {
  position: absolute;
  top: 4px;
  left: 4px;
}

.amap-page-container {
  position: relative;
}

.time_title{
  font-size: 14px;
  color: #606266;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.hidden >>> .el-upload--picture-card {
  display: none;
}
</style>
<style lang="scss" src="./style/Form.scss" scoped>

</style>
